package hong;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Arc;
import javafx.scene.shape.Circle;
import javafx.scene.text.Text;

import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;

public class TimeDownCtrl extends BorderPane implements Initializable {

    /**
     * 当前正在编辑的倒计时对象
     * null 没有正在编辑的对象
     */
    public static TimeDownCtrl timeDownEdit = null;
    @FXML
    Pane timePanel;
    @FXML
    Arc timeProgress;
    @FXML
    Circle bgCircle;
    String COLOR_EDIT_NO = "#666666";//灰色
    String COLOR_EDIT_YES = "#388ef4";//蓝色
    /**
     * 蓝色 #388ef4 可以编辑，灰色 #666666 禁止编辑
     * isRunning==false时才可以编辑
     */
    @FXML
    Circle timeEdit;
    @FXML
    Text timeTitle;
    @FXML
    Text timeText;
    @FXML
    ImageView btnReset;
    @FXML
    ImageView btnDel;
    @FXML
    ImageView btnRunStop;

    Image imgRun,imgStop;
//    当前版本不允许暂停
    boolean isRun = false;//开始按钮状态：开始、暂停
    boolean isRunning = false;//是否正在倒计时
    double startAngleParam = 450;//背景圆弧修正参数
    double startAngle = 0;//背景圆弧起始弧度
    double timeDown360 = 360;//背景圆弧总弧度数，用于直观显示剩余时间
    double timeDownLength = 360;//背景圆弧弧度，用于直观显示剩余时间
    double step = 2;//背景圆弧每次递减的弧度
    public static String STR_MAO_HAO = ":";
    public static String STR_ZERO = "0";
    /** title,hour,minute,second */
    int timeRefresh = 333;//刷新时间间隔
    int hour,minute,second;//当前剩余时间：时、分、秒
    double totalSecond = 60;//总时长，单位：秒
    long timeStart = 0;//开始倒计时时的毫秒数，每次暂停再开始时会改变，初始值为0
    long timeSurplus;//剩余时长的毫秒数
    long timeTotal=100;//总时长，单位：毫秒
    long timePauseStart = 0;//暂停时的时间戳
    Map<String,String> timeParam = null;

    public TimeDownCtrl(){
        try {
            imgRun = Constants.images.get("img_run");
            imgStop = Constants.images.get("img_stop");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void timeDel(){
        isRunning = false;
        isRun = false;
        TimeDesktopCtrl.tDesktop.timeDelete(timePanel);
        TimeDesktopCtrl.tDesktop.timeParams.remove(timeParam);
        Constants.audio.stop();
    }

    /**
     * 时间到了、重置
     */
    public void timeOver(){
        isRunning = false;
        isRun = false;
        btnRunStop.setImage(imgRun);
        timeEdit.setStyle("-fx-fill:"+COLOR_EDIT_YES+";-fx-stroke:"+COLOR_EDIT_YES+";");
    }
    public void timeEdit(){
        if(isRunning){
            return;
        }
        TimeDesktopCtrl.editID = Integer.parseInt(timeParam.get("editID"));
        TimeDesktopCtrl.tDesktop.timeEdit();
        timeDownEdit = this;
    }
    public void timeReset(){
        timeDownLength = 360;
        startAngle = 0;
        initTimes();
        repeatTime();
        timeOver();
        Constants.audio.stop();
    }
    public void timeRunStop(){
        if(isRunning){//正在倒计时
            if(isRun){//暂停
                isRun = false;
                timePauseStart = System.currentTimeMillis();
                btnRunStop.setImage(imgRun);
            }else{//开始
                isRun = true;
                //再次开始时向后推移开始计时的时间点
                timeStart += System.currentTimeMillis() - timePauseStart;
                btnRunStop.setImage(imgStop);
            }
        }else{
            new Thread(()->{
//                initTimes();
                timeStart = System.currentTimeMillis();
                timeEdit.setStyle("-fx-fill:"+COLOR_EDIT_NO+";-fx-stroke:"+COLOR_EDIT_NO+";");
                isRunning = true;
                isRun = true;
                step = 360/totalSecond;
                btnRunStop.setImage(imgStop);
                int is = 1000,im = 60 * is,ih = 60 * im;
                long tm;
                double tmpArc;
//                while (timeDownLength > 1){
                while (timeSurplus > 1){
                    try {
                        Thread.sleep(timeRefresh);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(isRun){
                        //计算圆弧
//                        timeDownLength -= step;
                        tmpArc = (double)timeSurplus / timeTotal;
                        timeDownLength = tmpArc * timeDown360;
                        startAngle = startAngleParam - timeDownLength;
                        //计算剩余时分秒
                        timeSurplus = timeTotal - (System.currentTimeMillis() - timeStart);
                        hour = (int) (timeSurplus / ih);
                        tm = timeSurplus - hour * ih;
                        minute = (int) (tm /im);
                        second = (int) ((tm - minute * im) / is) + 1;
                        //刷新时间
                        repeatTime();
                    }
                }
                timeDownLength = 0;
                second = 0;
                repeatTime();
                timeOver();
                Constants.audio.play();
            }).start();
        }
    }

    void repeatTime(){
        timeToStr();
        //刷新进度
        timeProgress.setStartAngle(startAngle);
        timeProgress.setLength(timeDownLength);
    }
    /**
     * 刷新时间
     */
    public void timeToStr(){
        StringBuffer sb = new StringBuffer();
        if(hour < 10){sb.append(STR_ZERO);}
        sb.append(hour);
        sb.append(STR_MAO_HAO);
        if(minute < 10){sb.append(STR_ZERO);}
        sb.append(minute);
        sb.append(STR_MAO_HAO);
        if(second < 10){sb.append(STR_ZERO);}
        sb.append(second);
        timeText.setText(sb.toString());
    }
    public void initTimes(){
        if(timeParam == null){timeParam = TimeDesktopCtrl.timeParams.get(TimeDesktopCtrl.timeParams.size());}
        timeTitle.setText(timeParam.get("title"));
        hour = Integer.parseInt(timeParam.get("hour"));
        minute = Integer.parseInt(timeParam.get("minute"));
        second = Integer.parseInt(timeParam.get("second"));
        timeRefresh = Integer.parseInt(timeParam.get("timeRefresh"));
        if(second > 60){
            second = second - 60;
            minute ++;
        }
        if(minute > 60){
            minute = minute - 60;
            hour ++;
        }
        if(hour > 99){
            hour = 99;
        }
        totalSecond = hour * 3600 + minute * 60 + second;
        timeTotal = (long) (totalSecond * 1000);
        timeSurplus = timeTotal;
        timeToStr();
    }
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initTimes();
    }
}
